﻿namespace FallingWordsGame
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using FallingWordsGame.Interfaces;   

    public abstract class GameObject : IMoveable, IRenderable
    {
        protected IList<Word> body;
        
        private GameObject()
        {
            this.Destroy = false;
        }

        protected GameObject(IList<Word> wordList)
            : this()
        {
            this.body = wordList;
            this.TopLeft = new Coords(0, 0);
        }

        protected GameObject(IList<Word> wordList, Coords topLeft)
            : this(wordList)
        {
            this.TopLeft = topLeft;
        }

        public bool Destroy { get; set; }

        public Coords TopLeft { get; private set; }

        public Word FirstNotGuessed()
        {
            return this.body.FirstOrDefault(x => !this.IsGuessed(x));
        }
        
        public void Update()
        {
            if(this.body.ToList().TrueForAll(x => this.IsGuessed(x)))
            {
                this.Destroy = true;
            }
        }

        public char[,] GetImage()
        {
            int maxLength = this.body.Max(x => x.Length);

            var image = new char[this.body.Count, maxLength];

            for (int i = 0; i < this.body.Count; i++ )
            {
                for(int j = 0; j < this.body[i].Length; j++)
                {
                    image[i, j] = this.body[i][j];
                }
            }

            return image;
        }

        public void Move()
        {
            this.TopLeft += new Coords(1, 0);
        }

        private bool IsGuessed(Word word)
        {
            return word.Text.ToList().TrueForAll(x => char.IsUpper(x) || x == '@');
        }
    }
}
